/**
 * 营销活动
 */
define(['../../model/fb_impressions_clicks_installs','../../common/service'],function(chartData, http){
    var CampaignGroups = {
   		init: function () {
            var _this = this;
			//列表管理
			var settings = {
                supportSorting: true,
                isCombSorting: false,
				sortUpText : 1,
				sortDownText: -1,
				supportDrag: false,
                //配置排序所需要的搜索事件源
                sortingCallback:  function (query, th) {
                	//排序存储的格式不同
					query['orderFiled'] = th.attr('th-name');
					query['orderType'] = th.attr('sorting');
					this.query['orderFiled'] = th.attr('th-name');
					this.query['orderType'] = th.attr('sorting');
					_this.getList(query);
                },
                supportAjaxPage: true,
                pageCallback: function(query){
					_this.getList(query);
                }
            };
            $('table[list-manager="litecampaigngroups"]').listManager('init', settings, function(query){
            	_this.pageDataForInitListManager = query;
            });
            //初始化配置[ztree插件]，并绑定与批次的二级联动
            _this.initZtreeToAppsAndConfigurations();
            //初始化时间[datepicker插件],并默认显示时间为当前时区的今天
            _this.timezoneId = window.sessionStorage.timezoneId + ':00';
            _this.timezoneValue = window.sessionStorage.timezoneValue;
            _this.getNowDate(function () {            //更新服务器时间
                _this.initDaterangepicker();        //初始化时间控件
                //时间控件显示使用默认值：今天
                var datepicker = $('#search-area').find('.datepicker');             //时间控件DOM
                var nowDate = moment(_this.nowDate).utcOffset(_this.timezoneValue).format('YYYY-MM-DD');
                var _daterangepicker = datepicker.data('daterangepicker');
                _daterangepicker.setStartDate(nowDate);
                _daterangepicker.setEndDate(nowDate);
                //绑定搜索事件，并将需要使用的插件进行初始化
                _this.bindSearchEvent();
            });
            //绑定更新功能
            _this.bindEditStatusEvent();

            /**
             * 绑定列表事件
             */
            _this.bindGirdEvent();

            $('#moreBtn').on('click', function () {
                if($('#moreTargetingMenu .selectdNode').length==0){
                    Kit.alert2('请选择目标或配置');
                    return false;
                }
            });
            //获取图表所需静态数据
			_this.getChartStaticData();
        }
   		/*
   		 @初始化ztree
   		 * */
		,initZtreeToAppsAndConfigurations: function () {
            var _this = this;
            //参数配置
            var setting = {
                view: {
                    dblClickExpand: false,
                    showLine: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    beforeExpand: beforeExpand,
                    onExpand: onExpand,
                    onCollapse: onCollapse,
                    onClick: onClick
                }
            };
            //获取数据
            function queryAllApps(callback) {
                var loadingArea = $('.bigdrop');
                Kit.loading.show(loadingArea);
            	http.work('/connectionobjects/searchAppsAndConfigurations',{},'POST').then(function(res){
            		Kit.loading.hide(loadingArea);
            		var data = res.data;
            		if(res.flag == 'success'){
            			if (!data || data.length == 0) {
                            return false;
                        }
            			/*
                        data = _.sortBy(data, function (item) {
                            return item.name.toLowerCase();
                        });
                        */
                        callback(data);
            		}else{
            			Kit.alert2(res.msg || '操作失败');
            		}
                });
            }

            var curExpandNode = null;
            //用于捕获父节点展开之前的事件回调函数，并且根据返回值确定是否允许展开操作
            function beforeExpand(treeId, treeNode) {
                var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
                var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
                var zTree = $.fn.zTree.getZTreeObj("treeView");
                for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
                    if (treeNode !== treeNodeP.children[i]) {
                        zTree.expandNode(treeNodeP.children[i], false);
                    }
                }
                while (pNode) {
                    if (pNode === treeNode) {
                        break;
                    }
                    pNode = pNode.getParentNode();
                }
                if (!pNode) {
                    singlePath(treeNode);
                }

            }

            function singlePath(newNode) {
                if (newNode === curExpandNode) return;
                if (curExpandNode && curExpandNode.open == true) {
                    var zTree = $.fn.zTree.getZTreeObj("treeView");
                    if (newNode.parentTId === curExpandNode.parentTId) {
                        zTree.expandNode(curExpandNode, false);
                    } else {
                        var newParents = [];
                        while (newNode) {
                            newNode = newNode.getParentNode();
                            if (newNode === curExpandNode) {
                                newParents = null;
                                break;
                            } else if (newNode) {
                                newParents.push(newNode);
                            }
                        }
                        if (newParents != null) {
                            var oldNode = curExpandNode;
                            var oldParents = [];
                            while (oldNode) {
                                oldNode = oldNode.getParentNode();
                                if (oldNode) {
                                    oldParents.push(oldNode);
                                }
                            }
                            if (newParents.length > 0) {
                                zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
                            } else {
                                zTree.expandNode(oldParents[oldParents.length - 1], false);
                            }
                        }
                    }
                }
                curExpandNode = newNode;
            }

            //用于捕获节点被展开的事件回调函数
            function onExpand(event, treeId, treeNode) {
                curExpandNode = treeNode;
                $('#tree').getNiceScroll().resize(); //重置滚动条
            }

            //用于捕获节点折叠的事件回调函数
            function onCollapse() {
                $('#tree').getNiceScroll().resize(); //重置滚动条
            }

            /**
             * 账号tree列表
             */
            function accountTree(accountList) {
                var self = this;
                var moreTagrtings = new Array();
                $.each(accountList, function (i, v) {
                    moreTagrtings.push({
                        id: v.fbAccountId,
                        name: v.displayName + "  (" + (v.timezone ? v.timezone : "") +"  )"
                    });
                });

                //初始化 高级定位 树状结构
                var moreTagrtingsElement = '';
                $.each(moreTagrtings, function (i, v) {
                    moreTagrtingsElement += '<li>';
                    if (v.children) {
                        //父
                        moreTagrtingsElement += '<a id="targetingParent" href="javascript:void(0);" style="padding-left: 8px;">'
                            + '<span id="icon" class="fa fa-caret-right" style="padding-right: 3px;"></span><span>' + v.name + '</span>'
//                            + '<span class="fa fa-check pull-right hide" style="margin-right: 1px;"></span>'
                            + '</a>';
                        //子
                        moreTagrtingsElement += '<ul id="targetingChildren" class="dropdown-list-submenu hide">';
                        $.each(v.children, function (index, child) {
                            moreTagrtingsElement += '<li class="selectdNode" selectd-node="' + child.id + '" checked="checked">';
                            moreTagrtingsElement += '<a href="javascript:void(0);"><span>' + child.name + '</span><span id="selectIcon" class="fa fa-check pull-right " style="margin-right: 20px;"></span></a>';
                            moreTagrtingsElement += '</li>';
                            $('#settingCtn').append('<div ctn="' + child.id + '" step-title="' + child.name + '" class="form-group" style="display:none;" ></div>');
                        });
                        moreTagrtingsElement += '</ul>';
                    } else {
                        moreTagrtingsElement += '<li class="selectdNode" selectd-node="' + v.id + '" checked="checked">';
                        moreTagrtingsElement += '<a href="javascript:void(0);"><span>' + v.name + '</span><span id="selectIcon" class="fa fa-check pull-right " style="margin-right: 1px;"></span></a>';
                        moreTagrtingsElement += '</li>';
                        $('#settingCtn').append('<div ctn="' + v.id + '" step-title="' + v.name + '" class="form-group" style="display:none;" ></div>');
                    }
                });
                moreTagrtingsElement += "</li>";
                $('#moreTargetingMenu').html(moreTagrtingsElement);

                //展开折叠事件
                $('#moreTargetingMenu #targetingParent').on('click', function () {
                    var childrenE = $(this).parent().find("#targetingChildren");
                    if (childrenE.hasClass("hide")) {
                        $(this).find("#icon").removeClass("fa-caret-right");
                        $(this).find("#icon").addClass("fa-caret-down");
                        childrenE.removeClass("hide");
                    } else {
                        $(this).find("#icon").removeClass("fa-caret-down");
                        $(this).find("#icon").addClass("fa-caret-right");
                        childrenE.addClass("hide");
                    }
                    return false;
                });

                //勾选事件 控制显示与否
                $('#moreTargetingMenu .selectdNode').on('click', function () {
                    var btn = $(this);
                    var ctn = $('div[ctn=' + btn.attr('selectd-node') + ']');
                    var selectIcon = $(this).find("#selectIcon");
                    selectIcon.toggleClass("hide");
                    if (selectIcon.hasClass("hide")) {
                        btn.removeAttr('checked')
                        ctn.hide();
                    } else {
                        btn.attr('checked', 'checked')
                        ctn.show();
                    }
                    $('#moreTargetingMenu').trigger('clickAccount');
                    return false;
                });

                $('#moreBtn').on('click', function () {
                    var treeMenu = $('#moreTargetingMenu #targetingParent');
                    $.each(treeMenu, function (i, v) {
                        var childrenE = $(this).parent().find("#targetingChildren");
                        childrenE.removeClass("hide");
                        $(this).trigger('click');
                    });
                });
            }


            //用于捕获节点被点击的事件回调函数
            function onClick(e, treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("treeView");
                zTree.expandNode(treeNode, null, null, null, true);
                var parentNode = treeNode.getParentNode();
                var tmpHtml = '';
                var newfbConnectionObjectId;
                var productCnfId;
                var platform;
                if (parentNode) {
                    //选择产品配置
                    tmpHtml = "<img style='margin:0 5px;' src='" + parentNode.icon + "' />"
                        + "<strong>"
                        + parentNode.name
                        + "</strong> / "
                        + treeNode.name;
                    newfbConnectionObjectId = parentNode.fbConnectionObjectId;
                    productCnfId = treeNode.id;
                    platform = treeNode.name;
                } else {
                    //选择应用
                    tmpHtml = "<img style='margin:0 5px;' src='" + treeNode.icon + "' />"
                        + "<strong>"
                        + treeNode.name
                        + "</strong>";
                    newfbConnectionObjectId = treeNode.fbConnectionObjectId;
                    productCnfId = -1;
                    platform = "";
                }

                var oldfbConnectionObjectId = $("#fbConnectionObjectId").val();
                if (oldfbConnectionObjectId != newfbConnectionObjectId) {
                    //当切换到新的应用
                    $("#fbConnectionObjectId").val(newfbConnectionObjectId);
                    //根据账号查询应用
                    var loadingArea = $('.bigdrop');
                    Kit.loading.show(loadingArea);
                    $("#account-list-title").addClass('hide');
                    var par = {
                        connObjId: newfbConnectionObjectId
                    };

           			http.work('/entrustaccounts/getAccounts',par,'POST').then(function(res){
           				var data = res.data;
           				if(res.flag == 'success'){
           					 var accountHtml = '';
                            //<span title="test1">test1;</span></p>
                            var isFirst = true;
							var _role = {};
							if(!data.accounts || data.accounts.length == 0){
								 Kit.alert2('找不到对应的账号信息');
								return false;
							}
                            data.accounts = _.sortBy(data.accounts, function (item) {
                                return item.timezone.toLowerCase();
                            });

                            $.each(data.accounts, function(i, account){
                                accountHtml += '<div class="col-sm-3 isShowAccount" style="min-height: 25px;" title="'+account.displayName+'">'+account.displayName+'</div>';
                                isFirst = false;
								_role[account.fbAccountId] = account.role;
                            });

							$("#account-list").data('role', _role);
                            $("#account-list").html(accountHtml);
                            accountTree(data.accounts);
                            _this.handleTimezone(data.accounts);
                            _this.dataAccounts = data.accounts;
                            //绑定帐号选择事件
                            $('#moreTargetingMenu').unbind('clickAccount');
                            $('#moreTargetingMenu').bind('clickAccount', function () {
                                var accountIds = [];
                                $('#moreTargetingMenu .selectdNode[checked=checked]').each(function () {
                                    accountIds.push($(this).attr('selectd-node'));
                                });
                                var accs = [];
                                for(var i=0;i<accountIds.length;i++){
                                    var selectEdId = accountIds[i];
                                    for(var j=0;i<_this.dataAccounts.length;j++){
                                        var acc = _this.dataAccounts[j];
                                        if(acc.fbAccountId==selectEdId){
                                            accs.push(acc);
                                            break;
                                        }
                                    }
                                }
                                _this.handleTimezone(accs,'noChangeDate');
                            });
           				}else{
           					Kit.alert2(res.msg || '操作失败');
           				}
           				Kit.loading.hide(loadingArea);
           			});
                }

                //显示选中内容
                $("#result").html(tmpHtml).data("node", treeNode);
                $("#productSelResult").val(productCnfId);
                $("#selectedPlatform").val(platform);
                //隐藏下拉树
                $("#tree").addClass("hide");
                $("#result").removeClass("choose_active");
                //获取批次信息，并渲染至DOM
                //  loadPublishBatch(treeNode.id);
            }

            queryAllApps(function (result) {
                var map = new Kit.hashMap();
                var configuration;
                var nodes = [],
                    parent = {},
                    node = {};
                $.each(result, function (i, d) {
                    nodes = [];
                    //默认取回来的图像大小是100px，需要转换为16px
                    //   var pic = d.picture.substring(0,d.picture.lastIndexOf("/")) + "/p16x16" + d.picture.substring(d.picture.lastIndexOf("/"),d.picture.length);
                    parent = {
                        id: "p-" + d.id,
                        pId: '',
                        fbConnectionObjectId: d.fbConnectionObjectId,
                        name: d.name,
                        icon: d.picture,
                        isParent: true
                    };
                    nodes.push(parent);
                    configuration = d.configurations;
                    for (var i = 0; i < configuration.length; i++) {
                        node = {
                            id: configuration[i].id,
                            pId: "p-" + d.id,
                            name: configuration[i].platform,
                            icon: "./imgs/icon-market.png",
                            objectStoreUrl: configuration[i].objectStoreUrl,
                            realName: configuration[i].platform
                        };
                        nodes = nodes.concat(node);
                    }
                    map.put(d.id, nodes);
                });
                //动态写入
                var zNodes = [];
                $("#tree").html("<ul id='treeView' class='ztree' ></ul>");
                $.each(map.values(), function (i, d) {
                    if (d !== null) {
                        $.each(d, function (i2, d2) {
                            zNodes.push(d2);
                        });
                    }
                });
                //显示为树
                $.fn.zTree.init($("#treeView"), setting, zNodes);
                //结果单击出现或者隐藏下拉框
                $("#productSel").click(function () {
                    $("#result").toggleClass("choose_active");
                    $("#tree").toggleClass("hide");
                });
                //美化滚动条效果
                $("#tree").niceScroll({
                    zindex: 10,
                    cursorwidth: 6,
                    cursorcolor: "#ABABAB",
                    cursorborder: "1px solid #BDBDBD",
                    enablemouselockapi: false,
                    horizrailenabled: false //屏蔽横向滚动条
                });
            })
        }
        /*
         @初始化时间控件
         */
        , initDaterangepicker: function (_startDate_,_endDate_) {
            var _this = this;
            //存储时区信息至widget属性
            var datepicker = $('#search-area .datepicker');
            if (!datepicker || datepicker.length == 0) {
                console.log('初始化时间控件失败，原因：未找到需要初始化的DOM节点');
                return false;
            }
            //生成快捷选择时间段
            //subtract方法会对调用对象进行修改，所以无法将moment(_this.nowDate).utcOffset(_this.timezoneValue)抽取为变量
            var today = moment(_this.nowDate).utcOffset(_this.timezoneValue).format('YYYY-MM-DD'),
                yesterday = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(1, 'days').format('YYYY-MM-DD'),
                forward_7_day = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(6, 'days').format('YYYY-MM-DD'),
                forward_30_day = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(29, 'days').format('YYYY-MM-DD'),
                thisMonthBegin = moment(_this.nowDate).utcOffset(_this.timezoneValue).startOf('month').format('YYYY-MM-DD'),
                thisMonthEnd = moment(_this.nowDate).utcOffset(_this.timezoneValue).endOf('month').format('YYYY-MM-DD'),
                lastMonthBedin = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(1, 'month').startOf('month').format('YYYY-MM-DD'),
                lastMonthEnd = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(1, 'month').endOf('month').format('YYYY-MM-DD');
            if(_startDate_&&_endDate_){
                datepicker.daterangepicker({
                    startDate:_startDate_,
                    endDate:_endDate_,
                    timePicker: false,
                    timezone: _this.timezoneValue,
                    format: 'YYYY-MM-DD',
                    separator: '至',
                    maxDate:today,
                    locale: {
                        applyLabel: '确定',
                        cancelLabel: '取消',
                        fromLabel: '所在时区：',
                        toLabel: _this.timezoneId,
                        customRangeLabel: '自定义',
                        daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                        monthNames: ['一月', '二月', '三月', '四月', '五月','六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                        firstDay: 0
                    }, ranges: {
                        '今天': [today, today],
                        '昨天': [yesterday, yesterday],
                        '前七天': [forward_7_day, today],
                        '前三十天': [forward_30_day, today],
                        '本月': [thisMonthBegin, thisMonthEnd],
                        '上月': [lastMonthBedin, lastMonthEnd]
                    }
                });
            }else{
                datepicker.daterangepicker({
                    timePicker: false,
                    timezone: _this.timezoneValue,
                    format: 'YYYY-MM-DD',
                    separator: '至',
                    maxDate:today,
                    locale: {
                        applyLabel: '确定',
                        cancelLabel: '取消',
                        fromLabel: '所在时区：',
                        toLabel: _this.timezoneId,
                        customRangeLabel: '自定义',
                        daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                        monthNames: ['一月', '二月', '三月', '四月', '五月','六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                        firstDay: 0
                    }, ranges: {
                        '今天': [today, today],
                        '昨天': [yesterday, yesterday],
                        '前七天': [forward_7_day, today],
                        '前三十天': [forward_30_day, today],
                        '本月': [thisMonthBegin, thisMonthEnd],
                        '上月': [lastMonthBedin, lastMonthEnd]
                    }
                });

            }
        }
        /**
        *处理账号时区是否支持查询和显示
        */
        ,handleTimezone:function(accounts, isChangeDate){
            var _this = this;
            if(accounts.length==0){
                return;
            }
            var timeZoneArr = [];
            _.each(accounts,function(account,i){
                timeZoneArr.push(account.timezoneStr);
            });
            var diff = _.union(timeZoneArr);
            if(isChangeDate){
                if(diff.length>1){
                    $("#search-action").addClass('disabled');
                    $("#differentTimeZone").removeClass("hide");
                }else{
                    var datepicker = $('#search-area').find('.datepicker');             //时间控件DOM
                    var _daterangepicker = datepicker.data('daterangepicker');
                    var startDate = moment(_daterangepicker.startDate).format('YYYY-MM-DD')    ;
                    var endDate = moment(_daterangepicker.endDate).format('YYYY-MM-DD')    ;

                    $("#search-action").removeClass('disabled');
                    $("#differentTimeZone").addClass("hide");
                    var _role = {};
                    $.each(accounts, function (i, account) {
                        _role[account.fbAccountId] = account.role;
                    });
                    $("#account-list").data('role', _role);
                    var acc = accounts[0];
                    _this.accountTimezone = Number(acc.timezoneOffset);
                    _this.timezone = acc.timezoneStr;
                    _this.timezoneId = acc.timezoneStr;
                    _this.timezoneValue = acc.timezoneStr;
                    console.log('handleTimezone1')
                    _this.initDaterangepicker(startDate,endDate);
                }
            }else{
                if(diff.length>1){
                    $("#search-action").addClass('disabled');
                    $("#differentTimeZone").removeClass("hide");
                }else{
                    $("#search-action").removeClass('disabled');
                    $("#differentTimeZone").addClass("hide");
                    var _role = {};
                    $.each(accounts, function (i, account) {
                        _role[account.fbAccountId] = account.role;
                    });
                    $("#account-list").data('role', _role);
                    var acc = accounts[0];
                    _this.accountTimezone = Number(acc.timezoneOffset);
                    _this.timezone = acc.timezoneStr;
                    _this.timezoneId = acc.timezoneStr;
                    _this.timezoneValue = acc.timezoneStr;
                    var datepicker = $('#search-area').find('.datepicker');             //时间控件DOM
                    var _daterangepicker = datepicker.data('daterangepicker');
                    var startDate = null;
                    var endDate = null;
                    startDate = moment(_this.nowDate).utcOffset(_this.timezone).format('YYYY-MM-DD');
                    endDate = startDate;
                    console.log('handleTimezone2')
                    _this.initDaterangepicker();
                    _daterangepicker.setStartDate(startDate);
                    _daterangepicker.setEndDate(endDate);
                }
            }
        }
        /**
         *获取服务器当前时间
         */
        , getNowDate: function (callback) {
            var _this = this;
            http.work('/common/timestamp',{},'POST').then(function(res){
            	var data = res.data;
				if(res.flag == 'success'){
					if (! data.date || data.date == '') {
                        return false;
                    }
                    _this.nowDate = data.date;
                    typeof(callback) == 'function' ? callback() : '';
				}else{
					Kit.alert2(res.msg || '操作失败');
				}
			});
        }
        /**
         * 绑定查询事件
         */
        , bindSearchEvent: function () {
            var _this = this;
            var searchArea = $('#search-area');	//搜索区域

            //1、搜索事件，并对条件进行验证
            var searchAction = searchArea.find('#search-action');                        //搜索事件触发源
            var productCnfId = searchArea.find('input[name="config"]');                  //目标配置
            var fbConnectionObjectId = searchArea.find('input[name="fbConnectionObjectId"]');    // 应用ID
            var selectedPlatform = searchArea.find('input[name="selectedPlatform"]');    // 平台
            var adGroupStatus = searchArea.find('select[name="adgroup-status"]');         // 应用ID
            var searchTime = searchArea.find('.datepicker');                           //时间
            var deleteAction = $('#delete-action');                        //删除事件触发源
            var pauseAction = $('#pause-action');                        //暂停事件触发源
            //绑定搜索事件
            searchAction.unbind('click');
            searchAction.bind('click', function () {
                _this.isCanSort = false;
                //表单验证
                if ('' == fbConnectionObjectId.val()) {
                    Kit.alert2('请选择目标或配置');
                    return false;
                }
                // 选择的广告账号
                var accountIds = [];
                if ($('#moreTargetingMenu .selectdNode[checked=checked]').length == 0) {
                        Kit.alert2('请选择账号!');
                        return;
                } else {
                    $('#moreTargetingMenu .selectdNode[checked=checked]').each(function () {
                        accountIds.push($(this).attr('selectd-node'));
                    });
                }

                _this.isCanSort = true;
                //查询今日总览
                var now = moment(_this.nowDate).utcOffset(_this.accountTimezone);
                var today = now.format('YYYY-MM-DD');
                var yesterday = now.subtract(1, 'days').format('YYYY-MM-DD');
                _this.yesterday = yesterday;
                _this.appProfile(productCnfId.val(), fbConnectionObjectId.val(), today);

                //查询列表
                //清空排序
                $('.sorting-up').removeClass('sorting-up');
                $('.sorting-down').removeClass('sorting-down');
                //设置默认排序
                $("th[th-name='spent']").find(".sorting-action", "div").addClass("sorting-down");

                var datepicker = $('#search-area').find('.datepicker');             //时间控件DOM
                var searchTimeData = datepicker.data('daterangepicker');

                var adgroupSearchType = $('form .adgroup-search-type').val();
                var adgroupSearchName = $('form input[name=adgroup-search-name]').val();

                var matches = [];
                if ('' != adgroupSearchName) {
                    var containSpecial = RegExp(/[(\*)(\.)(\?)(\+)(\$)(\^)(\[)(\])(\()(\))(\{)(\})(\|)(\\)(\/)]+/);
                    if (containSpecial.test(adgroupSearchName)) {
                        Kit.alert2("不支持的符号(*.?+$^\[](){}|\/)查询!", 'info');
                        return;
                    }
                    if (adgroupSearchType == 'campaign') {
                        var param = {"fieldName": "campaignGroupName", "matchValue": adgroupSearchName};
                        matches.push(param);
                    } else {
                        var param = {"fieldName": "adGroupName", "matchValue": adgroupSearchName};
                        matches.push(param);
                    }
                }

                var par = {
                    fbConnectionObjectId: fbConnectionObjectId.val(),
                    timeRange: {
                        since: moment(searchTimeData.startDate).format('YYYY-MM-DD'),
                        until: moment(searchTimeData.endDate).format('YYYY-MM-DD')
                    },
                    adGroupStatus: adGroupStatus.val(),
                    orderFiled: "spent", //默认按当日花费排序
                    orderType: -1,//默认降序
                    timezone: _this.timezone,
                    matches: matches,
                    accountIds: accountIds
                }

                if ('' != selectedPlatform.val()) {
                    par.platform = selectedPlatform.val();
                }
				$('table[list-manager="litecampaigngroups"]').listManager('getListManager').query = par;
                $('#grid').html('');
				_this.getAdGroupCount(par, function(){
					//pageDataForInitListManager 初始化listManager回调函数中返回的分页数据
                	_this.getList($.extend(true, {}, _this.pageDataForInitListManager, par));
				});

            });


            //绑定删除事件
            deleteAction.on('click', function () {
                _this.updateAdGroupByIds('delete', _this, searchAction)
            });
            //绑定暂停事件
            pauseAction.on('click', function () {
                _this.updateAdGroupByIds('pause', _this, searchAction)
            });

        }

        , updateAdGroupByIds: function (type, _this, searchAction) {
            $('.litecampaigngroups [name=adgroup-checkbox]:checkbox');
            var adGroupIds = [];
            $('.litecampaigngroups [name=adgroup-checkbox]:checkbox:checked').each(function () {
                adGroupIds.push($(this).val());
            });
            if (adGroupIds.length == 0) {
                return;
            }
            var action = '';//???
            if (type == 'delete') {
                action = 'deleteAdGroups';
            } else if (type == 'pause') {
                action = 'updateAdGroups';
            } else {
                return;
            }
            http.work('/adgroup/action', {ids: adGroupIds}, 'POST').then(function(res){
				var data = res.data;
				if(res.flag == 'success'){
					if (type == 'delete') {
                        Kit.alert_success('删除成功!');
                    } else if (type == 'pause') {
                        Kit.alert2('暂停成功!', 'info');
                    }
                    searchAction.trigger('click');
				}else{
					Kit.alert2(res.msg || '操作失败');
				}
			});
        }


        , appProfile: function (productCnfId, fbConnectionObjectId, day) {
            var _this = this;
            $('#today_profile').removeClass('hide');

            var par = {
                fbConnectionObjectId: fbConnectionObjectId,
                day: day
            };

            if ('' != productCnfId && -1 != productCnfId) {
                par.productCnfId = productCnfId;
            }
        }
        /**
         * 绑定列表框事件
         */
        , bindGirdEvent: function () {
            var _this = this;
            var litecampaigngroups = $('.litecampaigngroups');
            litecampaigngroups.off('click', '[name=adgroup-checkbox-all]:checkbox');
            litecampaigngroups.on('click', '[name=adgroup-checkbox-all]:checkbox', function (e) {
                e.stopPropagation();
                $("[name=adgroup-checkbox]:checkbox").prop("checked", this.checked);
            });
        }
        /**
         * 绑定编辑状态事件
         */
        , bindEditStatusEvent: function () {
            var _this = this;
            var _tbody = $('#grid');
            _tbody.off('click', '.toggle');
            _tbody.on('click', '.toggle', function (e) {
                var _toggle = $(this);
                if (_toggle.hasClass('no-click')) {
                    //无法点击
                    return false;
                }
                if (_toggle.hasClass('edit-ing')) {
                    //正在编辑
                    return false;
                }

                var _action = $('input[name="checkbox-toggle"]', _toggle),
                    _tr = _action.parents('tr').eq(0),
                    _adgroupId = _tr.attr('adgroup-id');
                var _statusElement = _action.get(0);
                var newStatus = !_statusElement.checked;
                var par = {
                    adGroupId: _adgroupId,
                    adGroupStatus: newStatus ? 'ACTIVE' : 'PAUSED'
                }
                var _loadIcon = $('<span class="fa fa-refresh refresh-rotation"></span>');
                _toggle.append(_loadIcon);
                _toggle.addClass('state-disabled');
                _toggle.addClass('edit-ing');
                http.work('/adgroup/updateAdGroup', par, 'POST').then(function(res){
					var data = res.data;
					if(res.flag == 'success'){
						if ('success' == data) {
                            _statusElement.checked = newStatus;
                        } else {
                            _statusElement.checked = !newStatus;
                        }
					}else{
                        _statusElement.checked = !newStatus;
						Kit.alert2(res.msg || '操作失败');
					}
					_toggle.removeClass('state-disabled');
                    _toggle.removeClass('edit-ing');
                    _loadIcon.fadeOut(300, function () {
                        $(this).remove();
                    });
				});
                return false;
            });
        }
        ,getAdGroupCount:function(par, callback){
            var _this = this;

            var loadingArea = $('.dt-wrapper');
            Kit.loading.show(loadingArea);
            http.work('/adgroupstats/getAdGroupCount', par, 'POST').then(function(res){
				var data = res.data;
				if(res.flag == 'success'){
					_this.adGroupCount = data.number || 0;
                	_this.adGroupCount == 0 ? '' : callback();
				}else{
					Kit.alert2(res.msg || '信息获取失败,请重试');
				}
				Kit.loading.hide(loadingArea);
			});
        }
        /*
         	@获取分页数据
         * */
        ,getPageData: function(pageData){
        	var _this = this;
			return {
				tPage: Math.ceil(_this.adGroupCount / pageData.pSize),				//总页数
		        cPage: pageData.cPage,				//当前页
		        pSize: pageData.pSize,				//每页显示条数
		        tSize: _this.adGroupCount			//总条数
			}
        }
        /*
         @获取列表数据
         */
        ,getList: function (par) {
            var _this = this;
            if (!_this.isCanSort && par.orderType) {
                $('.sorting-up').removeClass('sorting-up');
                $('.sorting-down').removeClass('sorting-down');
                return;
            }
            var loadingArea = $('.dt-wrapper');
            Kit.loading.show(loadingArea);
            http.work('/adgroupstats/getAdGroupStats', par, 'POST').then(function(res){
				var data = res.data;
				Kit.loading.hide(loadingArea);
				if(res.flag == 'success'){
					// 显示刷新频率和时间
                    if (data.refreshDatetime && data.refreshDatetimeFreq) {
                        var refreshHtml = '<label>刷新频率：</label><span>' + data.refreshDatetimeFreq + '分钟</span> &nbsp; &nbsp;<label>最近一次刷新时间：</label><span>' + data.refreshDatetime + '</span>';
                        $('#refreshTime').removeClass('hide').html(refreshHtml);
                    }

                    //操作DOM节点更换数据
                    var _tbody = $('#grid'),
                        tmpHtml = '',
                        _list = data.resultList;
                    if (_list.length == 0) {
                        Kit.alert2('没有数据!');
                        _tbody.html(tmpHtml);
                        return;
                    }

                    var adGroupIds = [];
                    $.each(_list, function (i, adgroupstat) {
                        adGroupIds.push(adgroupstat.adGroupId);
                        //    console.log(adgroupstat.adGroupName, _this.businessId, adgroupstat.campaignId, adgroupstat.adGroupId, par.timeRange);
                        //+ '<td><input type="checkbox" name="adgroup-checkbox" value="' + (adgroupstat.adGroupId || '') + '" /></td>'
                        tmpHtml += '<tr adgroup-id="' + (adgroupstat.adGroupId || '') + '" class="data">'
                            + '<td>'
                            + ((data.paginator.cPage-1) * data.paginator.pSize +i + 1)
                            + '</td>>'
                            + getAdGroupStatusHtml(adgroupstat.adGroupStatus, adgroupstat.accountId)
                            + getAdGroupNameHtml(adgroupstat.adGroupName, _this.getBusinessFromAccounts(adgroupstat.accountId), adgroupstat.campaignId, adgroupstat.adGroupId, par.timeRange)
                            + '<td title="' + (adgroupstat.adGroupId || '') + '">'
                            + (adgroupstat.adGroupId || '')
                            + '</td>'
                            + '<td title="' + (adgroupstat.campaignGroupName || '') + '">'
                            + adgroupstat.campaignGroupName
                            + '</td>'
                            + '<td title="' + Kit.formatNum(adgroupstat.uniqueImpressions) + '">'
                            + Kit.formatNum(adgroupstat.uniqueImpressions)
                            + '</td>'
                            + '<td title="' + Kit.formatNum(adgroupstat.clicks) + '">'
                            + Kit.formatNum(adgroupstat.clicks)
                            + '</td>'
                            + '<td title="' + Kit.formatNum(adgroupstat.impressions) + '">'
                            + Kit.formatNum(adgroupstat.impressions)
                            + '</td>'
                            + '<td title="' + Kit.formatNum(adgroupstat.ctr) + '">'
                            + Kit.percentage(adgroupstat.ctr)
                            + '</td>'
                            + '<td title="' + Kit.formatNum(adgroupstat.cr) + '">'
                            + Kit.percentage(adgroupstat.cr)
                            + '</td>'
                            + '<td title="' + Kit.formatNum(adgroupstat.results) + '">'
                            + Kit.formatNum(adgroupstat.results)
                            + '</td>'
                            + '<td name="cost" class="no_data" title="昨日统计数据...">'
                            + Kit.formatNum(Kit.cent_to_dollar(adgroupstat.cost))
                            + '$</td>'
                            + '<td title="' + Kit.formatNum(Kit.cent_to_dollar(adgroupstat.todaySpent)) + '">'
                            + Kit.formatNum(Kit.cent_to_dollar(adgroupstat.todaySpent))
                            + '$</td>'
                            + '<td name="total-spent" title="' + Kit.formatNum(Kit.cent_to_dollar(adgroupstat.spent)) + '">'
                            + Kit.formatNum(Kit.cent_to_dollar(adgroupstat.spent))
                            + '</td>';
//                            + '<td title="跳转至Facebook">'
//                            + '<a target="_blank" href="https://business.facebook.com/ads/manage/summary/adset/?business_id='+_list[i].fbBusinessId+'&ad_set_id='+_list[i].adSetId+'&show_adgroup_id='+_list[i].adGroupId+'&time_start='+_list[i].createTimeUtc+'&time_end='+_list[i].createTimeUtc+'"> 跳转至FB</a>'
//                            + '</td>';

                        //其它
                        tmpHtml += '</tr>';
                    });
                    _tbody.html(tmpHtml);

                    if ('ACTIVE' != par.adGroupStatus) {
                        $('#ad_group_table [th-name="adGroupStatus"]').listManager('hideTh');
                    } else {
                        $('#ad_group_table [th-name="adGroupStatus"]').listManager('showTh');
                    }
					$('table[list-manager="litecampaigngroups"]').listManager([{'resetTd':false,resetPageData: _this.getPageData(data.paginator)}]);
                    //初始化select
                    var selectDiv = "<div class='chart-select'><select class='form-control'><option value='7'>前七天</option><option value='30'>前三十天</option><option value='90'>前九十天</option></select></div>";
                    //初始化tabs

					var tabs = '<div class="bs-example bs-example-tabs" data-example-id="togglable-tabs">'
							 +'<ul id="myTabs" class="nav nav-tabs" role="tablist">'
							 +'<li role="presentation" class=""><a href="#Result" ad-chart-id="ad-chart-1" id="Result-tab" role="tab" data-toggle="tab" aria-controls="Result" aria-expanded="true">Result & Cost</a></li>'
      						+'<li role="presentation" class="active"><a href="#CTR" ad-chart-id="ad-chart-2" role="tab" id="CTR-tab" data-toggle="tab" aria-controls="CTR" aria-expanded="false">CTR</a></li>'
      					    + '</ul>'
    						+ '<div id="myTabContent" class="tab-content">'
    						+ '<div role="tabpanel" class="tab-pane fade active in" id="Result" aria-labelledby="Result-tab">'
							+ '<p><div id="ad-chart-1" class="ad-chart"/>' + selectDiv + '</p></div>'
    						+ '<div role="tabpanel" class="tab-pane fade" id="CTR" aria-labelledby="CTR-tab">'
							+ '<p><div id="ad-chart-2" class="ad-chart"/>' + selectDiv + '</p></div>'
                            + '</div></div></div></div>';
                    //绑定事件
                    $(".config-list").click(function () {
                        $("#ad-chart-row").remove();
                   //     _this.listManager.bindDragEvent($('[list-manager]'));
                    });
                    //添加表格事件
                    $("#grid tr").find("td[name!='exp']").click(function (e) {
                        // 避免选择复选框而打开图片
                        var adgroupCheckbox = $(e.currentTarget).find('[name=adgroup-checkbox]:checkbox');
                        if (adgroupCheckbox.length > 0) {// ????
                            if (!adgroupCheckbox[0].checked) {//去除全选
                                $('.litecampaigngroups [name=adgroup-checkbox-all]:checkbox').prop("checked", false);
                            }
                            return;
                        }
                        var obj = $(this).parent("tr");
                        if ($(obj).next("#ad-chart-row").get(0)) {
                            //已渲染
                            $("#ad-chart-row").remove();
                    //        _this.listManager.bindDragEvent($('[list-manager]'));
                            return;
                        } else {
                            $("#ad-chart-row").remove();
                        }
                        var _adGroupId = $(obj).attr("adgroup-id");
                        //1、显示
                        //计算合并列
                        var colNum = $(obj).find("td:visible").length;
                        var addHtml = "";
                        //判断有几列隐藏了
                        var hideTdLen = $("#grid").find("tr").eq(0).find("td:visible").eq(0).prevAll("td").length;
                        if (hideTdLen != 0) {
                            var tempStr = "";
                            for (var i = 0; i < hideTdLen; i++) {
                                tempStr += "<td></td>";
                            }
                            addHtml = "<tr id='ad-chart-row'>" + tempStr +
                                "<td colspan='" + colNum + "'>" +
                                "<div>" + tabs + "</div>"
                        } else {
                            addHtml = "<tr id='ad-chart-row'><td colspan='" + colNum + "'>" +
                                "<div>" + tabs + "</div>"
                        }
                        $(obj).after(addHtml);
                 //       $("#tabs").tabs();
                        // $("#ad-chart-row").show();

                        //2、加载数据
                        //如果已经加载过则不再加载

                        var _json = {};
                        var par = {
                            adGroupId: _adGroupId,
                            timeRange: {}
                        }
                        initChartData("ad-chart-1", par, 7);
                        //3、绑定组件
                        //绑定select事件
                        $(".chart-select select").change(function () {
                            var _selectObj = this;
                            var adChartId = $('.active .ad-chart', $(this).closest('.bs-example')).attr('id');
                            initChartData(adChartId, par, $(_selectObj).val());
                            /*
                            $("#tabs li").each(function () {
                                if ($(this).hasClass("ui-state-active")) {
                                    if ($(this).attr("name") == "tabs-1") {
                                        $.getJSON('../data/fb_impressions_clicks_installs.json', function (json) {
                                            _json = json;
                                            initChartData(_json, "ad-chart-1", par, $(_selectObj).val());
                                            $("#tabs li").eq(0).data("isOpened", true);
                                        });
                                    } else {
                                        $.getJSON('../data/fb_impressions_clicks_installs.json', function (json) {
                                            _json = json;
                                            initChartData(_json, "ad-chart-2", par, $(_selectObj).val());
                                        });
                                    }
                                }
                            });
                            */
                        });
                        //绑定tabs点击事件
                        /*
                        $("#tabs li").click(function () {
                            if (typeof ($(this).data("isOpened")) != "undefined") {
                                return;
                            } else {
                                $(this).data("isOpened", true);
                            }
                            if ($(this).attr("name") == "tabs-1") {
                                //result & click
                                var data = _json;
                                initChartData(data, "ad-chart-1", par, 7);
                            } else if ($(this).attr("name") == "tabs-2") {
                                var data = _json;
                                initChartData(data, "ad-chart-2", par, 7);
                            }
                        });
                        */
                        $('#myTabs a').click(function (e) {
							e.preventDefault();
                            initChartData(this.getAttribute('ad-chart-id'), par, 7);
							$(this).tab('show');
						})

                        //注掉表格拖拽事件
                        $('.drag-action').unbind("mousedown");
                    });
				}else{
					Kit.alert2(res.msg || '信息获取失败,请重试');
				}
			});
            //获取汇总数据
            http.work('/adgroupstats/getAdGroupStatistics', par, 'POST').then(function(res){
				var data = res.data;
				if(res.flag == 'success'){
					var html = '';
                    if(data){
                            html+='安装:'+data.results+'  &nbsp;&nbsp;&nbsp;';
                            html+='花费:'+Kit.formatNum(Kit.cent_to_dollar(data.spent))+'$  &nbsp;&nbsp;&nbsp;';
                            html+='成本:'+Kit.formatNum(Kit.cent_to_dollar(data.cost))+'$  &nbsp;&nbsp;&nbsp;';
                            //html+='覆盖人数:'+data.uniqueImpressions+'  &nbsp;&nbsp;&nbsp;';
                            html+='点击数:'+data.clicks+'  &nbsp;&nbsp;&nbsp;';
                            html+='展示数:'+data.impressions+'  &nbsp;&nbsp;&nbsp;';
                    }
                    $('#all-adgroup-result').html(html);
				}else{
					Kit.alert2(res.msg || '操作失败');
				}
			});

            function getTimeStemp(days) {
                var arr = [];
                for (var i = 0; i < days; i++) {
                    var t = moment(moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(days - i - 1, 'days').format('YYYY-MM-DD')).valueOf();
                    arr.push(t)
                }
                return arr;
            }

            function initChartData(domId, par, days) {
            	if(!_this.chartStaticData){   //如果_this.chartStaticData未获取成功，则进行再次获取
            		_this.getChartStaticData(function(){
            			initChartData(domId, par, days);
                        return;
            		});
            	}
                var loadingArea = $('table[list-manager="litecampaigngroups"]').closest('div');
                Kit.loading.show(loadingArea);
            	var json = $.extend(true, {}, _this.chartStaticData);
                var today = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(0, 'days').format('YYYY-MM-DD');
                var until;
                if (days == 7) {
                    //前七天
                    json.data[0].fields[0].unit = "timestamp";
                    until = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(6, 'days').format('YYYY-MM-DD');
                } else if (days == 30) {
                    json.data[0].fields[0].unit = "timestamp";
                    until = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(29, 'days').format('YYYY-MM-DD');
                } else if (days == 90) {
                    json.data[0].fields[0].unit = "week";
                    until = moment(_this.nowDate).utcOffset(_this.timezoneValue).subtract(89, 'days').format('YYYY-MM-DD');
                }
                par.timeRange.since = until;
                par.timeRange.until = today;
                var arr = getTimeStemp(days);
                json.data[0].rows = [];
                http.work('/adgroupstats/graphByAdgroup', par, 'POST').then(function(res){
					var _data = res.data;
					if(res.flag == 'success'){
						 //旋转显示指标
                        if (domId == "ad-chart-1") {
                            json.data[0].fields[1].name = "cost ($)";
                            json.data[0].fields[1].format.numericDecimals = 2;
                            json.data[0].fields[2].name = "result";
                            //json.data[0].fields[2].format.numericDecimals = 1;
                            //修改data数据
                            var beforeCost = 0;
                            for (var i = 0; i < arr.length; i++) {
                                var tempArr = [];
                                tempArr.push(arr[i]);
                                tempArr.push(_data.costs[i] / 100);
                                tempArr.push(_data.results[i] * 1.0);
                                if(i == arr.length - 1){
                                    tempArr.push(1);
                                }else{
                                    tempArr.push(0);
                                }
                                tempArr.push(_data.costs[i]/100);
                                tempArr.push(_data.results[i]*1.0);
                                //if(i == arr.length - 1){
                                //    tempArr.push(1);
                                //}else{
                                //    tempArr.push(0);
                                //}
                                json.data[0].rows.push(tempArr);
                                beforeCost = getMaxData(beforeCost, _data.costs[i] / 100);
                            }
                            if (beforeCost < (_data.vpi / 100)) {
                                beforeCost = _data.vpi / 100;
                            }
                            if (_data.vpi == 0) {
                                //移除CPI阈值线
                                json.grammar.coordinates.dimensions[0].axis[0].lineGuides = [];
                                json.grammar.coordinates.dimensions[0].axis[0].scale = {};
                            } else {
                                json.grammar.coordinates.dimensions[0].axis[0].lineGuides[0].value = _data.vpi / 100;
                                json.grammar.coordinates.dimensions[0].axis[0].scale.spans.max = beforeCost + (beforeCost * 1 / 3);
                            }
                            //console.log(beforeCost);
                            //console.log(json.grammar.coordinates.dimensions[0].axis[0].scale.spans.max);
                        } else if (domId == "ad-chart-2") {
                            json.data[0].fields[1].name = "ctr (%)";
                            json.data[0].fields[1].format.numericDecimals = 2;
//                             json.data[0].fields.pop();
                            for (var i = 0; i < arr.length; i++) {
                                var tempArr = [];
                                tempArr.push(arr[i]);
                                //tempArr.push(_data.clicks[i]);
                                tempArr.push(_data.ctr[i] * 100);
                                json.data[0].rows.push(tempArr);
                            }
                            //去除右边属性
                            json.grammar.coordinates.dimensions[0].axis.pop();
                            json.grammar.elements.pop();
                            //移除CPI阈值线
                            json.grammar.coordinates.dimensions[0].axis[0].lineGuides = [];
                            json.grammar.coordinates.dimensions[0].axis[0].scale = {};
                        }
                        var chartWidget = new ChartWidget();
                        var eventListener = new ChartEventListener();
                        chartWidget.addEventListener(eventListener);
                        chartWidget.placeAt($('#' + domId)[0]);
                        chartWidget.setVisJson(json);
                        window.setTimeout(function(){
                            $(window).trigger("resize");
                            Kit.loading.hide(loadingArea);

                        },500)
					}else{
						Kit.alert2(res.msg || '操作失败');
					}
				});
            }

            function getMaxData(cost, afterCost) {
                var _cost = cost;
                if (_cost < afterCost) {
                    _cost = afterCost;
                }
                return _cost;
            }

            function getAdGroupNameHtml(_adGroupName, _businessId, _adSetId, _adgroupId, _timeRange) {
                var adGroupNameHtml;
                if (_businessId & _adSetId & _adgroupId) {
                    adGroupNameHtml = '<td name="exp" title="' + (_adGroupName || '') + '">'
                        + '<a target="_blank" href="https://business.facebook.com/ads/manage/summary/adset/?business_id='
                        + _businessId + '&ad_set_id=' + _adSetId
                        + '&show_adgroup_id=' + _adgroupId + '&time_start=' + _timeRange.since + '&time_end=' + _timeRange.until + '">' + _adGroupName + '</a>'
                        + '</td>';
                } else {
                    adGroupNameHtml = '<td name="exp" title="' + (_adGroupName || '') + '">'
                        + (_adGroupName || '')
                        + '</td>';
                }

                return adGroupNameHtml;
            }

            function getAdGroupStatusHtml(_adGroupStatus, _accountId) {
                var roles = $("#account-list").data('role')
                var adGroupStatusHtml = '<td name="exp" >';
                if (roles[_accountId] == "REPORTS_ONLY") {
                    adGroupStatusHtml += '<label  class="update_adgroup_status toggle no-click" title="您的身份是广告分析员，不能修改广告状态" name="checkbox-toggle">'
                        + '<input type="checkbox"  disabled="disabled"/>';
                } else {
                    if ('ACTIVE' == _adGroupStatus) {
                        adGroupStatusHtml += '<label class="update_adgroup_status toggle">'
                            + '<input type="checkbox" name="checkbox-toggle" checked="checked"/>';
                    } else if ('PAUSED' == _adGroupStatus) {
                        adGroupStatusHtml += '<label class="update_adgroup_status toggle">'
                            + '<input type="checkbox" name="checkbox-toggle"/>';
                    } else {
                        adGroupStatusHtml += '<label  class="update_adgroup_status toggle no-click" title="该广告状态为' + _adGroupStatus + '，请跳转至FB修改" name="checkbox-toggle">'
                            + '<input type="checkbox"  disabled="disabled"/>';
                    }
                }
                adGroupStatusHtml += '<i data-swchon-text="ON" data-swchoff-text="OFF"></i>'
                    + '</label>'
                    + '</td>'
                return adGroupStatusHtml;
            }
        }
        /*
         	@获取图表静态数据
         * */
        ,getChartStaticData: function(callback){
        	var _this = this;
            _this.chartStaticData = chartData;
        	typeof(callback) == 'function' ? callback() : '';
        }
        /**
         * [getBusinessFromAccounts 从 accounts 得到对应的 businessId]
         * @return {[type]} [description]
         */
        ,getBusinessFromAccounts: function (fbAccountId) {
            var _this = this;
            if(_this.dataAccounts){
              for (var i = 0; i < _this.dataAccounts.length; i++) {
                var account = _this.dataAccounts[i]
                if(account.fbAccountId==fbAccountId){
                  return account.businessId;
                }
              }
            }
            return '';
        }
   }
   return CampaignGroups;
});
